import JsCookies from 'js-cookie'
import { SUCCESS, getLang as getLangApi, login, getUserInfo, logout, getSysParams, getUserState, getMessages } from '@/api'
import { numberUtils, deepObjectMerge } from '@/utils'
import Router from '@/router'
import { Locale } from 'vant'
import { getLang, defaultLang } from '@/lang'
import { setTheme, defaultTheme } from '@/theme'

let userInfo = null
try {
  userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
} catch (ex) {}

const state = () => ({
  lang: localStorage.getItem('lang') || defaultLang, //语言包
  api_token: JsCookies.get('api_token'),
  lastLogin: localStorage.getItem('lastLogin') || '',
  userInfo: userInfo,
  sysParams: {},
  version: '1.0.0', //App版本号
  chcpVersion: localStorage.getItem('chcpVersion') || '1', //热更新版本号,
  theme: localStorage.getItem('theme') || defaultTheme, //主题
  userState: {},
  message:0
})

const getters = {
  /*getLang(state) {
    return state.lang
  },*/
}

const mutations = {
  updateLang (state, lang) {
    state.lang = lang
  },
  updateApiToken (state, apiToken) {
    state.api_token = apiToken
  },
  updateUserInfo (state, userInfo) {
    state.userInfo = userInfo || {}
  },
  updateSysParams (state, sysParams) {
    state.sysParams = sysParams
  },
  updateVersion (state, version) {
    state.version = version
  },
  updateChcpVersion (state) {
    state.chcpVersion = numberUtils.add(state.chcpVersion, 1)
    localStorage.setItem('chcpVersion', state.chcpVersion)
  },
  updateTheme (state, theme) {
    state.theme = theme
  },
  updateUserState (state, userState) {
    state.userState = userState
  },
  updateMessage (state, total) {
    state.message = total
  },
}

const actions = {
  setLang({ commit, state }, local) {
    local = local || state.lang
    const Lang = getLang(local)
    localStorage.setItem('lang', local)
    commit('updateLang', local)
    $i18n.locale.value = local
    Locale.use(local, Lang.locale)
    getLangApi(local).then(res => {
      if(res){
        let _local = Lang.file
        _local = deepObjectMerge(_local, res)
        $i18n.setLocaleMessage(local, _local)
        localStorage.setItem(local, JSON.stringify(_local))
      }
    })
  },

  setApiToken({commit }, apiToken) {
    if (apiToken) {
      JsCookies.set('api_token', apiToken, {
        expires: 365 * 100
      })
      localStorage.setItem('isFirstLogin', true)
    } else {
      localStorage.removeItem('userInfo')
      JsCookies.remove('api_token')
    }
    commit('updateApiToken', apiToken)
  },

  setUserInfo({ commit }, userInfo) {
    if (userInfo) {
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
      localStorage.setItem('lastLogin', userInfo.username)
    } else {
      localStorage.removeItem('userInfo')
    }
    commit('updateUserInfo', userInfo)
  },

  // user login
  login({ dispatch, commit }, loginInfo) {
    return new Promise((resolve, reject) => {
      login(loginInfo).then(res => {
        if (res.rst === SUCCESS) {
          const apiToken = res.api_token
          dispatch('setApiToken', apiToken).then(() => {
            dispatch('getUserInfo').then(res2=>{
              resolve({apiToken, userInfo:res2})
            }).catch(res=>{
              reject()
            })

          })
        } else {
          reject()
        }
      })
    })
  },

  // get user info
  getUserInfo({dispatch, commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(res => {
        if (res.rst === SUCCESS) {
          dispatch('setUserInfo', res.data).then(() => {
            resolve(res.data)
          })
        } else {
          reject()
        }
      })
    })
  },

  // user logout
  logout({dispatch, commit, state}) {
    // logout(state.api_token).then(res=>{
      dispatch('setApiToken', null),
      dispatch('setUserInfo', null)
      Router.replace({name:'home', params:{active:0}})
    // })
  },

  setTheme({ commit,  state}, theme) {
    theme = theme || state.theme
    setTheme(theme)
    localStorage.setItem('theme', theme)
    commit('updateTheme', theme)
  },

  // get system params
  getSysParams({dispatch, commit, state }, showLoading=false) {
    return new Promise((resolve, reject) => {
      getSysParams(showLoading).then(res => {
        if (res.rst === SUCCESS) {
          let params = {timestamp: state.sysParams.timestamp || 0}
          for(let item of res.data){
            params[item.code] = item.value
          }
          commit('updateSysParams', params)
        }
        resolve(res)
      })
    })
  },

  // 获取用户状态
  getUserState({dispatch, commit, state }) {
    return new Promise((resolve, reject) => {
      getUserState().then(res => {
        if(res.rst == SUCCESS){
            commit('updateUserState', res.data)
        }
        resolve(res)
      })
    })
  },

  // 获取用户消息
  getMessages({dispatch, commit, state }, params) {
    return new Promise((resolve, reject) => {
      // 参数为空时获取所有未读消息
      getMessages(params).then(res => {
        if(res.rst == SUCCESS){
            commit('updateMessage', res.total)
        }
        resolve(res)
      })
    })
  },
}

export default {
  namespaced: true,
  getters,
  state,
  mutations,
  actions
}
